package org.lzy.shop.util

import android.content.Context
import android.graphics.Bitmap
import android.graphics.BitmapFactory
import org.lzy.shop.Constant
import top.zibin.luban.Luban
import top.zibin.luban.OnCompressListener
import java.io.File
import kotlin.math.ceil

/**
 * Created by dell on 2016/6/9.
 * 方便使用bitmap的工具类，提供了bitmap转换，缩略等实用的方法
 */
object BitmapUtils {
    /**
     * 根据路径转换为bitmap
     *
     * @param path
     * @return
     */
    @JvmStatic
    fun pathToBitmap(path: String?): Bitmap? {
        val options = BitmapFactory.Options()
        options.inJustDecodeBounds = true
        // Calculate inSampleSize
        options.inSampleSize = calculateInSampleSize(options, 480, 480)
        // Decode bitmap with inSampleSize set
        options.inJustDecodeBounds = false
        val bitmap = BitmapFactory.decodeFile(path, options)
        return bitmap
    }


    fun calculateInSampleSize(options: BitmapFactory.Options, reqWidth: Int, reqHeight: Int): Int {
        val height = options.outHeight
        val width = options.outWidth
        var inSampleSize = 1

        if (height > reqHeight || width > reqWidth) {
            val halfHeight = height / 2
            val halfWidth = width / 2

            // 计算最大的inSampleSize值，该值为2的幂，并保持宽高都大于或等于请求的宽高
            while (halfHeight / inSampleSize >= reqHeight && halfWidth / inSampleSize >= reqWidth) {
                inSampleSize *= 2
            }
        }

        return inSampleSize
    }

    fun getBitmap(path: String?): Bitmap? {
        //先解析图片边框的大小
        val ops = BitmapFactory.Options()
        ops.inJustDecodeBounds = true
        var bm = BitmapFactory.decodeFile(path, ops)
        ops.inSampleSize = 1
        val oHeight = ops.outHeight
        val oWidth = ops.outWidth
        //控制压缩比
        var contentHeight = 0
        var contentWidth = 0
        contentHeight = 640 //自定义
        contentWidth = 640 //自定义
        if ((oHeight.toFloat() / contentHeight) < (oWidth.toFloat() / contentWidth)) {
            ops.inSampleSize = ceil((oWidth.toFloat() / contentWidth).toDouble()).toInt()
        } else {
            ops.inSampleSize = ceil((oHeight.toFloat() / contentHeight).toDouble()).toInt()
        }
        ops.inJustDecodeBounds = false
        bm = BitmapFactory.decodeFile(path, ops)
        return bm
    }

    //拍照后压缩图片并上传，大小约300多K
    fun compressPicture(context: Context?, paths: String?, listener: OnCompressListener?) {
        if (!Constant.pictureFile.exists()) {
            val file = File(Constant.pictureFile.getPath())
            val mkdir = file.mkdirs()
            if (!mkdir) {
            }
        }
        // 传人要压缩的图片列表
        Luban.with(context)
            .load(paths) // 忽略不压缩图片的大小
            //不压缩的阈值，单位为K
            .ignoreBy(2 * 1024)
            .setTargetDir(Constant.pictureFilePath) // 设置压缩后文件存储位置
            .setCompressListener(listener).launch()
    }


}
